import { ConanCard, ConanCardSearchRequest } from "../../models/conan-card.model";
import { ConanCardService } from "../../services/conan-card.service";
import { GlobalService } from "../../services/global.service";

// pages/conan/conan.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cardList: [] as ConanCard[],
    idCountMap: {} as { [key: number]: number },
    popupVisible: false,
    hasMore: true,
    display: true,
    attributes: '',
    packages: '',
    needEnergyCountMax: 0,
    bpMax: 0,
    generateEnergyCountMax: 0,
    gridMode: true,
    FILE_HOST: GlobalService.STATIC_FILE_HOST,
  },

  customData: {
    cardList: [] as ConanCard[],
    filteredList: [] as ConanCard[],
    idCountMap: {} as { [key: number]: number },
    cardDeckNoCountMap: {} as { [key: string]: number },
    colorCount: 0,
    finalCount: 0,
    specialCount: 0,
    needEnergyCountMax: 0,
    bpMax: 0,
    generateEnergyCountMax: 0,
    init: false,
    searchRequest: {} as ConanCardSearchRequest,
    currentPage: 0,
    size: 18,
    totalPage: 0,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: any) {
    wx.setNavigationBarTitle({
      title: 'Conan'
    });
    this.customData.idCountMap = JSON.parse(JSON.stringify(GlobalService.ID_COUNT_MAP));
    this.customData.cardDeckNoCountMap = JSON.parse(JSON.stringify(GlobalService.DECKNO_COUNT_MAP));
    this.setData({
      idCountMap: this.customData.idCountMap,
      display: !!options.display
    });
    ConanCardService.getAll().then((response: ConanCard[]) => {
      const deckNos: string[] = [];
      const categorySet = new Set<string>();
      const packageSet = new Set<string>();
      for (const card of response) {
        if (!!this.customData.cardDeckNoCountMap[card.cardDeckNo!] && !deckNos.includes(card.cardDeckNo!)) {
          deckNos.push(card.cardDeckNo!);
        }
        for (const attr of card.category ?? []) {
          categorySet.add(attr);
        }
        packageSet.add(card.package ?? '');
      }

      let defaultSearchRequest = JSON.parse(JSON.stringify(GlobalService.DEFAULT_CONAN_SEARCH_REQ)) as ConanCardSearchRequest;
      if (this.data.display || !this.data.display && JSON.stringify(GlobalService.DEFAULT_SEARCH_REQ) === "{}") {
        defaultSearchRequest = {
          apMin: 0,
          apMax: 7000,
          costMin: 0,
          costMax: 8,
          lpMin: 0,
          lpMax: 2,
          color: undefined,
          type: undefined,
          package: '',
          rare: '',
          category: ''
        } as ConanCardSearchRequest;
      }
      this.customData.cardList = response;
      this.customData.filteredList = JSON.parse(JSON.stringify(response));
      this.customData.totalPage = Math.ceil(this.customData.filteredList.length / this.customData.size);
      const categoryList = [...categorySet];
      const packageList = [...packageSet];
      this.setData({
        cardList: JSON.parse(JSON.stringify(this.customData.filteredList.slice(0, this.customData.size))),
        defaultSearchRequest,
        categories: categoryList.length > 0 ? categoryList.join(',') : '',
        packages: packageList.length > 0 ? packageList.join(',') : '',
      });

    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    if (!this.data.display) {
      GlobalService.ID_COUNT_MAP = JSON.parse(JSON.stringify(this.customData.idCountMap));
      GlobalService.DECKNO_COUNT_MAP = JSON.parse(JSON.stringify(this.customData.cardDeckNoCountMap));
      GlobalService.DEFAULT_SEARCH_REQ = JSON.parse(JSON.stringify(this.customData.searchRequest));
    } else {
      GlobalService.clearCurrentEditingDeckInfo();
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.onLoadMore();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  openPopup() {
    this.setData({
      popupVisible: true
    });
  },

  onPopupVisibleChange(e: any) {
    this.setData({
      popupVisible: e.detail.visible,
    });
  },

  onSearch(e: any) {
    this.setData({
      popupVisible: false
    });
    this.customData.searchRequest = e.detail;
    this.filter();
    this.onRefresh();
  },

  onRefresh() {
    this.customData.currentPage = 0;
    this.cutlist();
  },

  onLoadMore() {
    if (!this.data.hasMore) {
      return;
    }
    this.customData.currentPage++;
    this.cutlist();
  },

  onReset(e: any) {
    this.customData.searchRequest = e.detail;
  },

  filter() {
    console.log(this.customData.searchRequest);
    const filterd: ConanCard[] = []
    for (const item of this.customData.cardList) {
      if (!!item.ap) {
        if (this.customData.searchRequest.apMin! > item.ap! || item.ap! > this.customData.searchRequest.apMax!) {
          continue;
        }
      } else {
        if (this.customData.searchRequest.apMin! !== 0) {
          continue;
        }
      }

      if (!!item.lp) {
        if (this.customData.searchRequest.lpMin! > item.lp! || item.lp! > this.customData.searchRequest.lpMax!) {
          continue;
        }
      } else {
        if (this.customData.searchRequest.lpMin! !== 0) {
          continue;
        }
      }

      if (!!item.cost) {
        if (this.customData.searchRequest.costMin! > item.cost! || item.cost! > this.customData.searchRequest.costMax!) {
          continue;
        }
      } else {
        if (this.customData.searchRequest.costMin! !== 0) {
          continue;
        }
      }

      if (!!this.customData.searchRequest.type && item.type !== this.customData.searchRequest.type) {
        continue;
      }

      if (!!this.customData.searchRequest.color && item.color !== this.customData.searchRequest.color) {
        continue;
      }

      if (!!this.customData.searchRequest.package && item.package !== this.customData.searchRequest.package) {
        continue;
      }

      if (!!this.customData.searchRequest.category && (!item.category || item.category.indexOf(this.customData.searchRequest.category) === -1)) {
        continue;
      }

      if (!!this.customData.searchRequest.rare && (!item.rare || item.rare !== this.customData.searchRequest.rare)) {
        continue;
      }

      filterd.push(item);
    }
    this.customData.filteredList = filterd;
    this.customData.totalPage = Math.ceil(filterd.length / this.customData.size);
  },

  cutlist() {
    const start = this.customData.currentPage * this.customData.size;
    const stop = start + this.customData.size;
    this.setData({
      cardList: JSON.parse(JSON.stringify(this.customData.filteredList.slice(0, stop))),
      hasMore: stop < this.customData.filteredList.length
    })
  },

  changeMode() {
    this.setData({
      gridMode: !this.data.gridMode
    })
  },

  onIncrease(e: any) {
    return;
    // const id = e.detail;
    // const card = this.customData.cardList.find((item: UaCard) => item.id === id);
    // if (!card) return;
    // if (!!card.triggerType) {
    //   let triggerFull = false;
    //   switch (card.triggerType) {
    //     case TriggerType.Color:
    //       triggerFull = this.customData.colorCount >= 4;
    //       if (!triggerFull) {
    //         this.customData.colorCount++;
    //       }
    //       break;
    //     case TriggerType.Final:
    //       triggerFull = this.customData.finalCount >= 4;
    //       if (!triggerFull) {
    //         this.customData.finalCount++;
    //       }
    //       break;
    //     case TriggerType.Special:
    //       triggerFull = this.customData.specialCount >= 4;
    //       if (!triggerFull) {
    //         this.customData.specialCount++;
    //       }
    //       break;
    //   }
    //   if (triggerFull) {
    //     Message.warning({
    //       context: this,
    //       offset: [20, 32],
    //       duration: 3000,
    //       content: `「${TriggerTypeMap[card.triggerType!]}」触发最多只能投入4张`,
    //     });
    //     return;
    //   }
    // }
    // if (!!card.cardConflict) {
    //   const conflictList = card.cardConflict.split(',');
    //   for (const deckNo of conflictList) {
    //     if (this.customData.cardDeckNoCountMap[deckNo]) {
    //       Message.warning({
    //         context: this,
    //         offset: [20, 32],
    //         duration: 3000,
    //         content: `卡组中存在「${deckNo}」，无法投入本卡片。`,
    //       });
    //       return;
    //     }
    //   }
    // }
    // if (!this.customData.cardDeckNoCountMap[card.cardDeckNo!]) {
    //   this.customData.cardDeckNoCountMap[card.cardDeckNo!] = 1;
    //   this.customData.idCountMap[card.id!] = 1;
    //   this.setData(
    //     { idCountMap: this.customData.idCountMap }
    //   );
    // } else {
    //   const count = +this.customData.cardDeckNoCountMap[card.cardDeckNo!];
    //   if (count >= card.limitCount!) {
    //     Message.warning({
    //       context: this,
    //       offset: [20, 32],
    //       duration: 3000,
    //       content: `「${card.cardName}(${card.cardDeckNo})」最多只能投入${card.limitCount}张`,
    //     });
    //     return;
    //   }
    //   this.customData.cardDeckNoCountMap[card.cardDeckNo!]++;
    //   if (this.customData.idCountMap[card.id!]) {
    //     this.customData.idCountMap[card.id!]++;
    //   } else {
    //     this.customData.idCountMap[card.id!] = 1;
    //   }
    //   this.setData(
    //     { idCountMap: this.customData.idCountMap }
    //   );
    // }
  },

  onDecrease(e: any) {
    return;
    // const id = e.detail;
    // const card = this.customData.cardList.find((item: UaCard) => item.id === id);
    // if (!card) return;
    // if (!this.customData.idCountMap[card.id!]) {
    //   return;
    // }
    // const count = +this.customData.idCountMap[card.id!];
    // if (count <= 0) {
    //   return;
    // }
    // if (!!card.triggerType) {
    //   switch (card.triggerType) {
    //     case TriggerType.Color:
    //       this.customData.colorCount--;
    //       if (this.customData.colorCount < 0) {
    //         this.customData.colorCount = 0;
    //       }
    //       break;
    //     case TriggerType.Final:
    //       this.customData.finalCount--;
    //       if (this.customData.finalCount < 0) {
    //         this.customData.finalCount = 0;
    //       }
    //       break;
    //     case TriggerType.Special:
    //       this.customData.specialCount--;
    //       if (this.customData.specialCount < 0) {
    //         this.customData.specialCount = 0;
    //       }
    //       break;
    //   }
    // }
    // this.customData.cardDeckNoCountMap[card.cardDeckNo!]--;
    // this.customData.idCountMap[card.id!]--;
    // this.setData(
    //   { idCountMap: this.customData.idCountMap }
    // );
  }
})